package com.haiertvbic.tvnow;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.haiertvbic.tvnow.adapter.ChannelLogoAdapter;
import com.haiertvbic.tvnow.anim.Rotate3DAnimation;
import com.haiertvbic.tvnow.cache.MyImage;
import com.haiertvbic.tvnow.cache.MyProgram;
import com.haiertvbic.tvnow.cache.MyProgress;
import com.haiertvbic.tvnow.cache.PIPCache;
import com.haiertvbic.tvnow.common.AppManager;
import com.haiertvbic.tvnow.common.Constant;
import com.haiertvbic.tvnow.holder.PIPHolder;
import com.haiertvbic.tvnow.holder.ScreenshortHolder;
import com.haiertvbic.tvnow.model.ChannelLogoBean;
import com.haiertvbic.tvnow.model.FavChannelBean;
import com.haiertvbic.tvnow.model.FavChannelPagekage;
import com.haiertvbic.tvnow.model.ProgramBean;
import com.haiertvbic.tvnow.network.EPGWeb;
import com.haiertvbic.tvnow.protocol.CAEProtocol;
import com.haiertvbic.tvnow.util.IsExit;
import com.haiertvbic.tvnow.util.LocateToast;
import com.haiertvbic.tvnow.util.SLog;
import com.haiertvbic.tvnow.util.SetActivityView;
import com.haiertvbic.tvnow.util.SwitchChannel;

public class TestTVNOWActivity1 extends Activity {
	// 没有获取频道数据
	private static final int GET_FAVCHAS_FAIL = 100000;
	// 获取频道数据成功
	private static final int GET_FAVCHAS_SUC = 100002;
	// 数据库错误
	private static final int DB_ERROR = 100003;
	// 未知错误
	private static final int NOT_SURE_ERROR = 100004;
	// 得台标
	protected static final int GET_LOGO_SUC = 100005;
	protected static final int GET_LOGO_FAIL = 100006;
	protected static final String TAG = "TVNOWActivity";

	private ListView chann_lv;
	private ListView chann_logo_lv;
	private PopupWindow pop;
	public static View fView;
	private View child_view;
	private Context context = TestTVNOWActivity1.this;
	private String checkCid;
	private int sreen_height;
	private Handler pip_handler;
	private Animation inAnimation = null;
	private Timer pip_tt;
	private ArrayList<View> itemViews = new ArrayList<View>();
	private PIPHolder pip;
	private boolean canToNext;
	private boolean canSwitch;
	private int which;
	private int currentCha = -200;
	private int switchCha = -200;
	private FrameLayout anim1;
	// 控制pip动画新图显示
	private boolean flag1 = true;
	private boolean flag2 = true;
	private boolean flag3 = true;
	private boolean burshShow1 = true;
	private boolean burshShow2 = true;
	private boolean burshShow3 = true;
	// ==========拆分动画显示=================
	private ArrayList<MyProgram> list_pro;
	private ArrayList<MyProgress> list_progress;
	private ArrayList<MyImage> list2;
	private ArrayList<FavChannelBean> favChannels;
	private Handler myHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case GET_FAVCHAS_FAIL:
				Toast.makeText(
						TestTVNOWActivity1.this,
						getResources()
								.getString(R.string.get_chann_data_failed),
						Toast.LENGTH_SHORT).show();
				break;
			case GET_LOGO_SUC:// 得到台标
				ArrayList<ChannelLogoBean> logos = (ArrayList<ChannelLogoBean>) msg.obj;
				if (logos != null) {
					SLog.d(TAG, "传来的台标信息不为空,长度为" + logos.size());
					chann_logo_lv.setAdapter(new ChannelLogoAdapter(logos,
							context, sreen_height));
				}
				break;
			case GET_LOGO_FAIL:// 得不到台标
				// 获取频道数据失败，消失加载数据进度条
				no_network.setVisibility(View.VISIBLE);
				no_network.setText(R.string.getLogoFail);
				break;
			case GET_FAVCHAS_SUC:
				// 获取数据成功，适配显示数据，消失加载数据的进度条
				no_network.setVisibility(View.GONE);
				if (favChannels != null && favChannels.size() > 0) {
					list2 = new ArrayList<MyImage>();
					list_pro = new ArrayList<MyProgram>();
					list_progress = new ArrayList<MyProgress>();
					for (int i = 0; i < favChannels.size(); i++) {
						String str = favChannels.get(i).getChannel_id() + "";
						MyProgram mypro = new MyProgram(adapter, context, str);
						list_pro.add(mypro);
						MyImage my2 = new MyImage(adapter, str, context);
						list2.add(my2);
						MyProgress myprogress = new MyProgress(adapter,
								context, str);
						list_progress.add(myprogress);
					}
					chann_lv.setAdapter(adapter);
					chann_lv.setVisibility(View.VISIBLE);
					chann_lv.requestFocus();
					chann_logo_lv.setVisibility(View.GONE);
					// if (WebData.getNetworkInfo(context)) {
					// chann_lv.setAdapter(adapter);
					// chann_lv.setVisibility(View.VISIBLE);
					// chann_logo_lv.setVisibility(View.GONE);
					// } else {
					// no_network.setVisibility(View.VISIBLE);
					// }
				}

				// ---------------------假环境测试-------------------------------------------------------------------
				// if (logos != null) {
				// list2 = new ArrayList<MyImage>();
				// list_pro = new ArrayList<MyProgram>();
				// list_progress = new ArrayList<MyProgress>();
				// for (int i = 0; i < logos.size(); i++) {
				// String str = logos.get(i).getCid();
				// MyImage my2 = new MyImage(adapter, str, context);
				// list2.add(my2);
				// MyProgram mypro = new MyProgram(adapter, context,
				// str);
				// list_pro.add(mypro);
				// MyProgress myprogress = new MyProgress(adapter,
				// context, str);
				// list_progress.add(myprogress);
				// chann_lv.setAdapter(adapter);
				// chann_lv.setVisibility(View.VISIBLE);
				// chann_logo_lv.setVisibility(View.GONE);
				// }
				// }
				// ---------------------------------------------------------------------------------------------------
				// 第二种方式
				canToNext = true;
				canSwitch = true;
				break;
			case DB_ERROR:
				// 数据库错误
				Toast.makeText(TestTVNOWActivity1.this,
						getResources().getString(R.string.db_error),
						Toast.LENGTH_SHORT).show();
				break;
			case NOT_SURE_ERROR:
				// 不确定的错误
				Toast.makeText(TestTVNOWActivity1.this,
						getResources().getString(R.string.Indeterminate_error),
						Toast.LENGTH_SHORT).show();
				break;

			case 0:
				LocateToast.locateToast(TestTVNOWActivity1.this, 200, getResources()
						.getString(R.string.read_change_msg_failed));
				break;

			case 4004500:
				LocateToast.locateToast(TestTVNOWActivity1.this, 200, getResources()
						.getString(R.string.change_success));
				currentCha = switchCha;
				break;

			case 4004501:
				LocateToast.locateToast(TestTVNOWActivity1.this, 200, getResources()
						.getString(R.string.channel_non_existent));
				break;

			case 4004502:
				LocateToast.locateToast(TestTVNOWActivity1.this, 200, getResources()
						.getString(R.string.please_connect_crb));
				break;

			case 4004503:
				LocateToast.locateToast(TestTVNOWActivity1.this, 200, getResources()
						.getString(R.string.no_set_crb));
				break;

			case -2002:
				LocateToast.locateToast(TestTVNOWActivity1.this, 200, getResources()
						.getString(R.string.connect_break_off));
				break;

			default:
				break;
			}
		}
	};
	private final BaseAdapter adapter = new BaseAdapter() {
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ScreenshortHolder holder = new ScreenshortHolder();
			if (convertView == null) {
				convertView = View.inflate(context, R.layout.screenshort_item,
						null);
				// =========动态控制图片张数=================
				holder.sc_chan_item_ll = (RelativeLayout) convertView
						.findViewById(R.id.sc_chan_item_ll);
				android.view.ViewGroup.LayoutParams ll_lp = holder.sc_chan_item_ll
						.getLayoutParams();
				ll_lp.height = (sreen_height - Constant.RANGE_TOP)
						/ Constant.CHANNEL_NUMBER;// 要减去控件的高度
				holder.sc_chan_item_ll.setLayoutParams(ll_lp);
				// =========动态控制图片张数=================
				holder.pip_iv = (ImageView) convertView
						.findViewById(R.id.pip_iv);
				// 字的背景颜色
				holder.screenshort_background_ll = (LinearLayout) convertView
						.findViewById(R.id.screenshort_background_ll);
				holder.pro_tv = (TextView) convertView
						.findViewById(R.id.pro_tv);
				holder.pro_stime_tv = (TextView) convertView
						.findViewById(R.id.pro_stime_tv);
				holder.pip_pb = (ProgressBar) convertView
						.findViewById(R.id.pip_pb);

				convertView.setTag(holder);
			} else {
				holder = (ScreenshortHolder) convertView.getTag();
			}
			if (list2.get(position).image != null) {
				list2.get(position).image = holder.pip_iv;
			} else {
				SLog.d(TAG, "没得倒图片了");
				holder.pip_iv.setImageResource(R.drawable.tv_now);
			}
			// ===============================================
			ProgramBean pro = list_pro.get(position).pro;
			if (pro != null) {
				holder.pro_tv.setText(pro.getPn());
				holder.pro_stime_tv.setText(pro.getPstime());
			}
			holder.pip_pb.setProgress(list_progress.get(position).progress);
			// ===============================================
			return convertView;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public Object getItem(int position) {
			// return list_pro.get(position).pro;
			return favChannels.get(position);
		}

		@Override
		public int getCount() {
			return favChannels.size();
		}
	};
	private TextView no_network;
	private int sreen_width;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		initview();
		// executeTime();//初始化定时器
		AppManager.activityList.add(this);
		EPGWeb.initSdcarDir(context);
		fView = SetActivityView
				.setActivityView(getWindow(), getWindowManager());

		sreen_height = getWindowManager().getDefaultDisplay().getHeight();
		sreen_width = getWindowManager().getDefaultDisplay().getWidth();
		// 获取频道信息
		getFavChaFromCae();
		inAnimation = AnimationUtils.loadAnimation(this, R.anim.slide_in_right);
		anim1.setAnimation(inAnimation);
		anim1.startAnimation(inAnimation);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		SLog.d(TAG, "============onResume=================");
		// 重新给定时器赋值
		executeTime();
		super.onResume();
	}

	private void executeTime() {
		if (Constant.IMAGE_TT == null) {
			Constant.IMAGE_TT = new Timer();
			if (favChannels != null && favChannels.size() > 0) {
				list2 = new ArrayList<MyImage>();
				for (int i = 0; i < favChannels.size(); i++) {
					String str = favChannels.get(i).getChannel_id() + "";
					MyImage my2 = new MyImage(adapter, str, context);
					list2.add(my2);
				}
			}
			SLog.d(TAG, "Constant.IMAGE_TT定时器开启了");
		}
		if (Constant.PIC_TT == null) {
			Constant.PIC_TT = new Timer();
			if (favChannels != null && favChannels.size() > 0) {
				list_pro = new ArrayList<MyProgram>();
				for (int i = 0; i < favChannels.size(); i++) {
					String str = favChannels.get(i).getChannel_id() + "";
					MyProgram mypro = new MyProgram(adapter, context, str);
					list_pro.add(mypro);
				}
			}
			SLog.d(TAG, "Constant.PIC_TT定时器开启了");
		}
		if (Constant.PROGRESS_TT == null) {
			Constant.PROGRESS_TT = new Timer();
			if (favChannels != null && favChannels.size() > 0) {
				list_progress = new ArrayList<MyProgress>();
				for (int i = 0; i < favChannels.size(); i++) {
					String str = favChannels.get(i).getChannel_id() + "";
					MyProgress myprogress = new MyProgress(adapter, context,
							str);
					list_progress.add(myprogress);
				}
			}
			SLog.d(TAG, "Constant.PROGRESS_TT定时器开启了");
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		SLog.d(TAG, "============onPause=======执行exitgetScreen===========");
		super.onPause();
		exitgetScreen();
	}

	private void exitgetScreen() {
		if (Constant.IMAGE_TT != null) {
			Constant.IMAGE_TT.cancel();
			Constant.IMAGE_TT = null;
			SLog.d(TAG, "Constant.IMAGE_TT定时器停了");
		}
		if (Constant.PIC_TT != null) {
			Constant.PIC_TT.cancel();
			SLog.d(TAG, "Constant.PIC_TT定时器停了");
			Constant.PIC_TT = null;
		}
		if (Constant.PROGRESS_TT != null) {
			Constant.PROGRESS_TT.cancel();
			SLog.d(TAG, "Constant.PROGRESS_TT定时器停了");
			Constant.PROGRESS_TT = null;
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		SLog.d(TAG, "============onDestroy==================");
		dismissPopWindow();
		exitgetScreen();
		super.onDestroy();
	}

	/**
	 * 填充截图的方法，第二种
	 * 
	 * @param logos
	 */

	/**
	 * 填充截图的方法，填充时只放了当前节目和频道号， 截图和进度自己算
	 * 
	 * @param logos
	 */

	private void getFavChaFromCae() {
		Thread getFavChasThread = new Thread() {

			@Override
			public void run() {
				// 46，44，43
				// String str = "46@44@43@5@1";
				// SLog.d(TAG, "请求的台标号是======" + str);
				// ArrayList<ChannelLogoBean> logos = EPGWeb.getChannelLogoXML(
				// context, str);
				// Message logo_msg = Message.obtain();
				// logo_msg.what = GET_FAVCHAS_SUC;
				// logo_msg.obj = logos;
				// myHandler.sendMessage(logo_msg);
				// favChannels = new ArrayList<FavChannelBean>();
				favChannels = new ArrayList<FavChannelBean>();
				int[] cid = { 4, 44, 43, 46, 6 };
				for (int i = 0; i < cid.length; i++) {
					FavChannelBean fav = new FavChannelBean();
					fav.setChannel_id(cid[i]);
					favChannels.add(fav);
				}
				if (favChannels != null) {
					myHandler.sendEmptyMessage(GET_FAVCHAS_SUC);
				}
				super.run();

				FavChannelPagekage favChaPkg = null;
				if (favChaPkg == null) {
					// 获取数据失败
					myHandler.sendEmptyMessage(GET_FAVCHAS_FAIL);
				} else if (favChaPkg.getReturn_code() == 4006002
						|| favChaPkg.getReturn_code() == 4006003) {
					// 操作数据库失败
					myHandler.sendEmptyMessage(DB_ERROR);
				} else if (favChaPkg.getReturn_code() == 4006000
						|| favChaPkg.getReturn_code() == 4006001) {
					favChannels = favChaPkg.getChannels();

					// ======================得台标=======================================
					if (favChannels != null) {
						// 得倒喜爱节目的id号，用来得倒台标路径
						String str = null;
						for (int i = 0; i < favChannels.size(); i++) {
							// 得倒id，在得台标
							String str1 = "";
							str1 = String.valueOf(favChannels.get(i)
									.getChannel_id());
							str = str + "@" + str1;
						}
						SLog.d(TAG, "请求的台标号是======" + str);
						ArrayList<ChannelLogoBean> logos = EPGWeb
								.getChannelLogoXML(context, str);
						if (logos != null) {
							Message logo_msg = Message.obtain();
							logo_msg.what = GET_LOGO_SUC;
							logo_msg.obj = logos;
							myHandler.sendMessage(logo_msg);
						} else {
							myHandler.sendEmptyMessage(GET_LOGO_FAIL);
						}
						myHandler.sendEmptyMessage(GET_FAVCHAS_SUC);// 发送得截图的信息
					}
					// ======================得台标=======================================

				} else if (favChaPkg.getReturn_code() == 4006004) {
					// 发生未知错误
					myHandler.sendEmptyMessage(NOT_SURE_ERROR);
				}

			}

		};
		getFavChasThread.start();
	}

	/**
	 * 初始化布局，显示带image的listview
	 */
	private void initview() {
		anim1 = (FrameLayout) findViewById(R.id.anim1_ll);
		chann_lv = (ListView) findViewById(R.id.chann_lv);
		chann_lv.setDivider(new ColorDrawable(Color.TRANSPARENT));
		chann_logo_lv = (ListView) findViewById(R.id.chann_logo_lv);
		no_network = (TextView) findViewById(R.id.no_network);
		chann_logo_lv.setDivider(new ColorDrawable(Color.TRANSPARENT));
		chann_lv.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {// TODO Auto-generated method stub
				int cha_id = Integer.valueOf(favChannels.get(arg2)
						.getChannel_id());
				SLog.d(TAG, "cha_id == " + cha_id);
				SLog.d(TAG, "canSwitch == " + canSwitch);
				if (canSwitch && currentCha != cha_id) {
					SwitchChannel.switchChannel(TestTVNOWActivity1.this, cha_id,
							myHandler);
					switchCha = cha_id;
				}
				// ProduceThread.seconds = Constant.SECOND_TIME;
			}
		});
		chann_lv.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				dismissPopWindow();
				child_view = arg1;
				which = arg2;
				itemViews.add(arg1);
				FavChannelBean fav = null;
				fav = (FavChannelBean) arg0.getAdapter().getItem(arg2);
				if (fav != null) {
					checkCid = fav.getChannel_id() + "";
					SLog.d(TAG,
							"onItemSelected选中的cid是=====" + fav.getChannel_id());
				}
				// 得倒那个返回的view并把颜色改了
				ScreenshortHolder holder = new ScreenshortHolder();
				for (int i = 0; i < itemViews.size(); i++) {
					if (itemViews.get(i) != arg1) {
						holder = (ScreenshortHolder) itemViews.get(i).getTag();
						holder.screenshort_background_ll
								.setVisibility(View.GONE);
						holder.pro_tv.setTextColor(0x00FFFFFF);// 不被选中时的字颜色
						holder.pro_stime_tv.setTextColor(0x00FFFFFF);// 不被选中时的字颜色
					} else {
						if (arg1 != null && arg1.getTag() != null) {
							holder = (ScreenshortHolder) arg1.getTag();
							holder.screenshort_background_ll
									.setBackgroundResource(R.color.red_color);
							// 0xFFFF1966是红色海尔；0x00333333是灰色的，
							holder.pro_tv.setTextColor(Color.WHITE);// 白色
							holder.pro_stime_tv.setTextColor(Color.WHITE);
							holder.screenshort_background_ll
									.setVisibility(View.VISIBLE);
						}

					}
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

	public void dismissPopWindow() {
		if (pop != null && pop.isShowing()) {
			pop.dismiss();
			pop = null;
		}
		if (pip_tt != null) {
			pip_tt.cancel();
			pip_tt = null;
		}
	}

	private boolean anim_over() {
		Animation outAnimation = AnimationUtils.loadAnimation(this,
				R.anim.slide_in_left);
		outAnimation.setFillAfter(true);
		fView.setAnimation(outAnimation);
		fView.startAnimation(outAnimation);
		return true;
	}

	private void showPopWindow() {
		pip = new PIPHolder();
		final View connvert = LayoutInflater.from(context).inflate(
				R.layout.channel_pop, null);
		initPIP(pip, connvert);
		pip_handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case 12:
					ArrayList<Bitmap> bm_pip = null;
					bm_pip = (ArrayList<Bitmap>) msg.obj;
					if (bm_pip != null) {
						SLog.d(TAG, "bm_pip得倒的截图长度为===" + bm_pip.size());
						fillPipPicData(pip, bm_pip);
					}
					break;

				default:
					break;
				}
			}
		};
		pip_tt = new Timer();
		pip_tt.schedule(new TimerTask() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				ArrayList<Bitmap> bm_pips;
				bm_pips = PIPCache.getPips(checkCid, context);
				SLog.d(TAG, "当前的cid是====" + checkCid);
				if (bm_pips != null) {
					Message msg = Message.obtain();
					msg.what = 12;
					msg.obj = bm_pips;
					pip_handler.sendMessage(msg);
				}
			}
		}, 0, 1000 * 10);
		int[] arrayOfInt = new int[2];
		if (child_view != null) {
			child_view.getLocationInWindow(arrayOfInt);
			int iii = (sreen_height - Constant.RANGE_TOP)
					/ Constant.CHANNEL_NUMBER;// 减去最上方控件的高度
			// 当条目被选中弹出popwindow
			pop = new PopupWindow(connvert, 320 * 2, iii);// 35是节目名称和节目时间的高度
			pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
			pop.showAtLocation(child_view, Gravity.LEFT | Gravity.TOP,
					arrayOfInt[0], arrayOfInt[1]);// 高度需要往上在调一点
			SLog.d(TAG, "arrayOfInt[0]===" + arrayOfInt[0]);
			SLog.d(TAG, "arrayOfInt[1]=======" + arrayOfInt[1]);
		}
	}

	private void fillPipPicData(final PIPHolder pip, final ArrayList<Bitmap> bms) {
		int centerX = pip.channel_pop_iv1.getLayoutParams().width >> 1;
		int centerY = pip.channel_pop_iv1.getLayoutParams().height >> 1;
		if (bms.size() == 3) {
			flag1 = true;
			final Animation anim1 = new Rotate3DAnimation(centerX, centerY,
					Rotate3DAnimation.ROTATE_DECREASE);// true
			// anim1.setFillAfter(true);
			anim1.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					pip.channel_pop_iv1.setVisibility(View.VISIBLE);
					burshShow1 = false;
				}
			});
			pip.channel_pop_iv1.postDelayed(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					((Rotate3DAnimation) anim1)
							.setInterpolatedTimeListener(new Rotate3DAnimation.InterpolatedTimeListener() {
								@Override
								public void interpolatedTime(
										float interpolatedTime) {
									if (burshShow1) {
										pip.channel_pop_iv1
												.setAlpha(interpolatedTime);
									} else {
										if (interpolatedTime <= 0.5) {
											pip.channel_pop_iv1
													.setAlpha((0.5f - interpolatedTime) / 0.5f);
										} else if (interpolatedTime > 0.5) {
											pip.channel_pop_iv1
													.setAlpha((interpolatedTime - 0.5f) / 0.5f);
										}
									}
									if (flag1 & interpolatedTime > 0.5f) {
										pip.channel_pop_iv1.setImageBitmap(bms
												.get(2));// 翻转后的新图
										flag1 = false;
									}
								}
							});
					// anim1.setStartOffset(1000);// 使动画延时显示
					// pip.channel_pop_iv1.setImageBitmap(bms.get(3));
					// pip.channel_pop_iv1.clearAnimation();
					pip.channel_pop_iv1.startAnimation(anim1);
				}
			}, 1000 * 2);

		}

		// ==========第二个动画======================================
		if (bms.size() > 2) {
			centerX = pip.channel_pop_iv2.getLayoutParams().width >> 1;
			centerY = pip.channel_pop_iv2.getLayoutParams().height >> 1;
			final Animation anim2 = new Rotate3DAnimation(centerX, centerY,
					Rotate3DAnimation.ROTATE_DECREASE);
			AnimationSet translate_rotate2 = new AnimationSet(true);
			TranslateAnimation translate = new TranslateAnimation(sreen_width, 0, 0, 0);
			translate.setDuration(1000 * 2);
			anim2.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {
					if (burshShow2)
						pip.channel_pop_iv2.setImageBitmap(bms.get(1));
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					pip.channel_pop_iv2.setVisibility(View.VISIBLE);
					burshShow2 = false;
				}
			});
			flag2 = true;
			// anim2.setFillAfter(true);
			((Rotate3DAnimation) anim2)
					.setInterpolatedTimeListener(new Rotate3DAnimation.InterpolatedTimeListener() {
						@Override
						public void interpolatedTime(float interpolatedTime) {
							if (burshShow2)
								pip.channel_pop_iv2.setAlpha(interpolatedTime);
							if (flag2 & interpolatedTime > 0.5f) {
								pip.channel_pop_iv2.setImageBitmap(bms.get(1));// 翻转后的新图
								flag2 = false;
							}
						}
					});
			Animation inanim = AnimationUtils.loadAnimation(context,
					R.anim.brush);
			translate_rotate2.addAnimation(inanim);
			translate_rotate2.addAnimation(translate);
			translate_rotate2.addAnimation(anim2);
			// translate_rotate2.setStartOffset(1000);
			// pip.channel_pop_iv2.setImageBitmap(bms.get(2));
			// pip.channel_pop_iv2.clearAnimation();
			if (burshShow2) {
				pip.channel_pop_iv2.startAnimation(translate_rotate2);
				// burshShow2 = false;
			} else {
				pip.channel_pop_iv2.startAnimation(anim2);
			}
		}

		// ==========第三个动画======================================
		if (bms.size() > 2) {
			centerX = pip.channel_pop_iv3.getLayoutParams().width >> 1;
			centerY = pip.channel_pop_iv3.getLayoutParams().height >> 1;
			final Animation anim3 = new Rotate3DAnimation(centerX, centerY,
					Rotate3DAnimation.ROTATE_INCREASE);// false
			anim3.setAnimationListener(new AnimationListener() {
				@Override
				public void onAnimationStart(Animation animation) {
				}

				@Override
				public void onAnimationRepeat(Animation animation) {
				}

				@Override
				public void onAnimationEnd(Animation animation) {
					// pip.channel_pop_iv3.setVisibility(View.VISIBLE);
					burshShow3 = false;
				}
			});
			// anim3.setStartOffset(2000);
			pip.channel_pop_iv3.postDelayed(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					flag3 = true;
					anim3.setFillAfter(true);
					((Rotate3DAnimation) anim3)
							.setInterpolatedTimeListener(new Rotate3DAnimation.InterpolatedTimeListener() {
								@Override
								public void interpolatedTime(
										float interpolatedTime) {
									if (burshShow3)
										pip.channel_pop_iv3
												.setAlpha(interpolatedTime);
									if (flag3 & interpolatedTime > 0.5f) {
										pip.channel_pop_iv3.setImageBitmap(bms
												.get(0));// 翻转后的新图
										flag3 = false;
									}
								}
							});
					pip.channel_pop_iv3.setImageBitmap(bms.get(1));
					pip.channel_pop_iv3.clearAnimation();
					pip.channel_pop_iv3.startAnimation(anim3);
				}
			}, 1000);
		}

	}

	private void initPIP(final PIPHolder pip, View connvert) {
		int pip_width = sreen_width / 5;
		int pip_height = sreen_height / 5;
		// ==========取控件==============
		pip.channel_pop_iv1 = (ImageView) connvert
				.findViewById(R.id.channel_pop_iv1);
		pip.channel_pop_iv2 = (ImageView) connvert
				.findViewById(R.id.channel_pop_iv2);
		pip.channel_pop_iv3 = (ImageView) connvert
				.findViewById(R.id.channel_pop_iv3);

		// ==========设置控件1的大小==============
		android.view.ViewGroup.LayoutParams lp1 = pip.channel_pop_iv1
				.getLayoutParams();
		lp1.width = pip_width;
		lp1.height = pip_height;
		pip.channel_pop_iv1.setLayoutParams(lp1);
		// ==========设置控件2的大小==============
		android.view.ViewGroup.LayoutParams lp2 = pip.channel_pop_iv2
				.getLayoutParams();
		lp2.width = pip_width;
		lp2.height = pip_height;
		pip.channel_pop_iv2.setLayoutParams(lp2);
		// ==========设置控件3的大小==============
		// ==========设置动画的大小==============
		android.view.ViewGroup.LayoutParams lp3 = pip.channel_pop_iv3
				.getLayoutParams();
		lp3.width = pip_width;
		lp3.height = pip_height;
		pip.channel_pop_iv3.setLayoutParams(lp3);
		// ==========设置动画的大小==============
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		SLog.d(TAG, "所按按键值===========" + keyCode);
		if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
			burshShow1 = true;
			burshShow2 = true;
			burshShow3 = true;
			dismissPopWindow();
			showPopWindow();
			// 防止用户多次按右键获取图片导致内存泄漏
			// try {
			// Thread.sleep(1000 * 2);
			// } catch (InterruptedException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }

		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			// Toast.makeText(ChannelProActivity.this, "DPAD_BACK",
			// 1000).show();
			// ProduceThread.canRun = false;
			// ProduceThread.exit = false;
			// IsExit.isExit(this);
		} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
			if (canToNext) {
				dismissPopWindow();
				Intent intent = new Intent();
				intent.putExtra("CHA_NAME", favChannels.get(which)
						.getChannel_name());
				intent.putExtra("CHA_ID", favChannels.get(which)
						.getChannel_id());
				SLog.d(TAG, "传给第二屏的频道id是："
						+ favChannels.get(which).getChannel_id());
				intent.setClass(this, SecondActivity.class);
				startActivity(intent);
				SLog.v(TAG, "跳转第二个界面");
				if (pip_tt != null) {
					pip_tt.cancel();
					pip_tt = null;
				}
				fView.setVisibility(View.GONE);
			}
		}
		return super.onKeyDown(keyCode, event);
	}
}